package com.hsj.springai.controller;

import com.hsj.springai.service.AsyncService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import lombok.SneakyThrows;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

@RestController
@Slf4j
public class AsyncController {

    @Autowired
    private AsyncService asyncService;


    @GetMapping("/test")
    @SneakyThrows
    public String testAsync(){
        return asyncService.testAsync();
    }

    @GetMapping("/sendEmails")
    @SneakyThrows
    public String shenEmails() {
        List<String> list = Arrays.asList("zhangsan@163.com", "lisi@163.com", "11233@qq.com");
        list.forEach(email -> asyncService.sendEmail(email, "你好，感谢关注！"));
        log.info("当前线程执行结束 ，返回成功给前端");
        return "success";
    }

    @GetMapping("/blockSendEmails")
    @SneakyThrows
    public String blockSendEmail() {
        //创建一个空数组，用于存储各个线程执行后返回的结果
        CompletableFuture<String>[] result = new CompletableFuture[5];
        List<String> list = Arrays.asList("zhangsan@163.com", "lisi@163.com", "11233@qq.com", "8808@1688.com", "123123@qq.com");
        for (int i = 0; i < list.size(); i++) {
            //将每次调用返回的结果放入数组
            result[i] = asyncService.blockSendEmail(list.get(i), "你好，感谢关注！");
        }
        //只有当数组里的结果都得到后才可以继续执行，，这里会阻塞
        CompletableFuture.allOf(result);
        //输出结果
        Arrays.stream(result).forEach(item -> {
            try {
                System.out.println(item.get());
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } catch (ExecutionException e) {
                throw new RuntimeException(e);
            }
        });
        return "success";
    }

}
